<template>
  <div v-if="selectedType">
    <TypeSelect v-model="varlike.type" :options="paras" mb2/>
    <VarInput v-model:varlike="varlike"/>
  </div>
</template>

<script setup lang="ts">
import type { WritableComputedRef } from 'vue';
import { VarInit } from "~/models/data/var_init";
import type { DataType } from '~/models/types/type';
import type { UnionType } from '~/models/types/union_type';

const props = defineProps<{
  type: DataType
  modelValue: any
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', event: any): void,
}>()

const t = computed(() => props.type as UnionType)
const paras = t.value.parallels

const selectedType = ref(null as DataType | null)
watch(selectedType, val => {
  console.log('selectedType', val);
  
})

// 设置最初的明确类型为：接受当前数据类型的
watch(props.type, (val) => {
  const types = (val as UnionType).parallels
  for (const paraType of types) {
    if (paraType.receiveValue(props.modelValue)) {
      selectedType.value = paraType
    }
  }
}, { immediate: true })



const varlike: WritableComputedRef<VarInit, VarInit> = computed({
  get(): VarInit {
    return new VarInit('', selectedType.value!, props.modelValue)
  },
  set(gvar) {
    console.log('union', gvar);
    
    selectedType.value = gvar.type
    emit('update:modelValue', gvar.initial)
  }
})
</script>

<style lang="scss">
.var-input-choice {
  width: 120px;
  background: #fff;
  border-radius: 4px;
  overflow: hidden;
  outline: none;
  .el-select__wrapper {
    color: #000;
  }
  .el-select__selected-item.el-select__placeholder {
    color: #000;
  }
}
</style>